/*
	digital_dist_sens.h
	author: Jared Bayne (JaredNBayne@gmail.com)
	initial draft: April 3rd, 2009
	
	
	functions for communicating to the digital 
	distance sensors we will use on the front
	and back of the robot.
	
	The reason we need this function is because we ran out of 
	ADC ports for our analog sensors.  Technically we have enough,
	but there are probelms with some of them that I can't figure out.
	So we're using a couple digital sensors to get the job done.
	
	GP2D02 IR Sensor
	Green wire is input
	Yellow wire is output


*/
#include <math.h>


#define 	front_data 			GET_BIT(PORTD).bit4	//yellow wire
#define 	trigger  			GET_BIT(PORTD).bit6	//green wire
#define 	back_data  			GET_BIT(PORTD).bit7	//yellow wire

//public functions
int take_reading_front(void);
int take_reading_back(void);
void digital_dist_tester(void);

//global variables
int front_dist =0, back_dist=0;

int take_reading_front(void)
{
/*
	1) Triggers the two digital distance sensors
	2) Reads serial data line in

*/
	int front_dist =0;


	trigger = OFF; 	//lower input line
	while(front_data!=ON);	//wait for readings to finish...data lines go high when readings finished
	for (int i =7; i>=0; i--)
	{
		trigger = ON;	//ask for next bit
		_delay_us(90);	//wait for middle of bit width
		front_dist += (back_data*pow(2,i));
		_delay_us(90);
		trigger = OFF;
		_delay_us(90);	//pause before next reading
	
	}
	_delay_ms(3);	//wait 3 ms before next reading...probably don't need this most of the time since we won't be calling this func one after another, but just to make sure
	return front_dist;
}

int take_reading_back(void)
{
/*
	1) Triggers the two digital distance sensors
	2) Reads serial data line in

*/
	int back_dist=0;


	trigger = OFF; 	//lower input line
	while(back_data!=ON);	//wait for readings to finish...data lines go high when readings finished
	
	for (int i =7; i>=0; i--)
	{
		trigger = ON;	//ask for next bit
		_delay_us(90);	//wait for middle of bit width
		back_dist += (back_data*pow(2,i));
		_delay_us(90);
		trigger = OFF;
		_delay_us(90);	//pause before next reading
	
	}
	_delay_ms(3);	//wait 3 ms before next reading...probably don't need this most of the time since we won't be calling this func one after another, but just to make sure
	return back_dist;	
}



void digital_dist_tester(void)
{

	writeln("see usart out");
	
	usart_writeln("edge_front: ",1);
	usart_disp_int(take_reading_front(),1);
	

	usart_write("    edge_front: ",1);
	usart_disp_int(take_reading_back(),1);
	


}